<?php
/**
 * Хендлер для получения всех сотрудников компании
 **/ 
class EditOrganizationHandler extends WallrideHandler{

  protected
    $action = false,
    $organizationId = false,
    $orgName = false,
    $orgParentId = false,
    $orgDescription = false,
    $orgHeadUserId = false,
    $companyId = false;

	public function setParams($params){  
    if (!empty($params['action'])) $this->action = $params['action'];
    if (!empty($params['orgName'])) $this->orgName = $params['orgName'];
    if (!empty($params['orgDescription'])) $this->orgDescription = $params['orgDescription'];
    if (!empty($params['orgHeadUserId']) && isUUID($params['orgHeadUserId']))
        $this->orgHeadUserId = $params['orgHeadUserId'];
    if (!empty($params['organizationId']) && isUUID($params['organizationId']))
        $this->organizationId = $params['organizationId'];
    if (!empty($params['orgParentId']) && isUUID($params['orgParentId']))
        $this->orgParentId = $params['orgParentId'];
    if (!empty($params['companyObj']) && !empty($params['companyObj']->data['company_id']))
        $this->companyId = $params['companyObj']->data['company_id'];
    
	}

	public function process(){
    if (!$this->action) return false;

    require_once('models/organization/organization.php');

    if ($this->action == 'modify_organization'){
      // Редактирование
      if (!$this->organizationId) return false;
      if ($this->organizationId == $this->orgParentId) return false; //ай-ай! так нельзя.
      
      $org = OrganizationModel::getByID($this->organizationId);
      if (!$org){
        Logger::error("Could not find organization {$this->organizationId} in EditOrganizationHandler \n".var_export($this, true));
        return false;
      }
      $org->data['name'] = $this->orgName;
      $org->data['description'] = $this->orgDescription;
      /**
       * @TODO EditOrganizationHandler - Проверять входящие ID на наличие в БД. Чтоб чужого мусора не насыпали.
       */
      $org->data['head_user_id'] = $this->orgHeadUserId ? $this->orgHeadUserId : null;
      $org->data['parent_id'] = $this->orgParentId ? $this->orgParentId : null;
      $res = $org->save();
      return $res;
    }
    elseif ($this->action == 'new_organization'){
      // Добавление нового объекта
      if (!$this->companyId) return false;

      $org = OrganizationModel::create(array(
         'name'=>$this->orgName,
         'description'=>$this->orgDescription,
         'company_id'=>$this->companyId,
         'parent_id'=>$this->orgParentId ? $this->orgParentId : null,
      ));
      if ($org) return true;
    }


    require_once 'models/organization/organization.php';

    return true;
	}

}
?>
